package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.poi.excel.Excel;
import com.ccp.dev.core.poi.excel.editor.IFontEditor;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import com.ccp.dev.core.poi.excel.style.Color;
import com.ccp.dev.core.poi.excel.style.DataFormat;
import com.ccp.dev.core.poi.excel.style.font.BoldWeight;
import com.ccp.dev.core.poi.excel.style.font.Font;
import com.ccp.dev.core.poi.excel.util.ExcelUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.TimeUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.extend.service.ExtendSysOrgService;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.expimp.CustomExcelReader;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AbstractImpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.WFlightRewardsProject;
import com.ccp.dev.qbdms.model.WQbdSoftwareView;
import com.ccp.dev.qbdms.model.WQbdXhdh;
import com.ccp.dev.qbdms.service.WCustomColumnsService;
import com.ccp.dev.qbdms.service.WQbdSoftwareViewService;
import com.ccp.dev.qbdms.service.WQbdXhdhService;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.service.DictionaryService;
import com.ccp.dev.system.service.SysOrgService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 软件概况 信息操作处理控制器
 *
 * @author hw
 * @date 2020-07-07 13:25:24
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "软件概况")
@RequestMapping("/qbdms/wQbdSoftwareView")
public class WQbdSoftwareViewController extends SysBaseController{
    @Resource
    private WQbdSoftwareViewService wQbdSoftwareViewService;
    @Resource
    private DictionaryService dictionaryService;
    @Resource
    private WQbdXhdhService wQbdXhdhService;
    @Resource
    private SysOrgService sysOrgService;
    @Resource
    private ExtendSysOrgService extendSysOrgService;
    @Resource
    private WCustomColumnsService wCustomColumnsService;
    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2020-07-07 13:25:24
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到软件概况首页", exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request, ModelMap modelMap) {
        wCustomColumnsService.addCustomCols(request);
        selectDic(modelMap);
        modelMap.put("currentUserId", ContextUtil.getCurrentUserId());
        modelMap.put("currentSystemLevel",BaseUtil.getCurrentSystemLevel());
        return "wQbdSoftwareView/list";
    }

    /**
     * 功能描述: 附带检索条件的分页查询
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: hw
     * @date: 2020-07-07 13:25:24
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="附带检索条件的分页查询软件概况",detail="查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request,ModelMap modelMap) {
        QueryFilter queryFilter = new QueryFilter(request, true);
        //分页数据
        ZhiLiangConst.addQueryFilter(queryFilter);
        List<Dictionary> xhmcList = getXhdhToDicList();
        List<WQbdSoftwareView> pageDatas = wQbdSoftwareViewService.queryList(queryFilter);
        pageDatas.stream().forEach(s->{
            xhmcList.forEach(a -> {
                if (a.getItemValue().equals(s.getModel())) {
                    s.setModel(a.getItemName());
                }
            });
        });
        try {
            ZhiLiangConst.showName(pageDatas);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }

    private void setDicToModelMap(String key, ModelMap modelMap) {
        List<Dictionary> dicList = dictionaryService.getDicByNodeKey(key, false);
        modelMap.put(key + "List", JSON.toJSONString(dicList));
    }
    public List<Dictionary> getXhdhToDicList(){
        List<WQbdXhdh> xhdhList = wQbdXhdhService.getAll();
        List<Dictionary> dicList = new ArrayList<>();
        for(WQbdXhdh wQbdXhdh : xhdhList){
            Dictionary dictionary = new Dictionary();
            dictionary.setItemName(wQbdXhdh.getfModelname());
            dictionary.setItemValue(wQbdXhdh.getId());
            dicList.add(dictionary);
        }
        return dicList;
    }

    public void selectDic(ModelMap modelMap){
        //        密级
//        setDicToModelMap("mj", modelMap);
        //型号名称
        List<Dictionary> xhmcList = getXhdhToDicList();
        modelMap.put("xhmcList", JSON.toJSONString(xhmcList));
        //软件研制阶段
        setDicToModelMap("rjyzjd", modelMap);
//        软件类型
        setDicToModelMap("rjlx", modelMap);
//        关键等级
        setDicToModelMap("gjdj", modelMap);
//        测评项目类型
        setDicToModelMap("cpxmlx", modelMap);
        // 数据来源单位
        List<Dictionary> originOrgToDicList = extendSysOrgService.getOriginOrgToDicList();
        modelMap.put("originOrgList", JSON.toJSONString(originOrgToDicList));
    }



    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: 于金
     * @date: 2020-07-06 09:53:26
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到软件概况新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        selectDic(modelMap);
        modelMap.put("id",id);
        if(id.isEmpty()){
            modelMap.put("dept",ContextUtil.getCurrentOrg().getOrgName());
        }
        return "wQbdSoftwareView/add";
    }

    /**
     * 功能描述:  数据保存通用方法
     *
     * @param: wQbdSoftwareView 保存的对象
     * @return: java.lang.Object
     * @auther: hw
     * @date: 2020-07-07 13:25:24
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存软件概况数据",detail="<#if isAdd>新增<#else>编辑</#if>软件概况数据<#if success>成功<#else>失败</#if ><#if StringUtil.isNotEmpty(modifyInfo)>${modifyInfo}</#if>")
    public Object save(@RequestBody WQbdSoftwareView wQbdSoftwareView) throws IllegalAccessException {
        String id = wQbdSoftwareView.getId();
        int result;
        BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
        if (StringUtil.isEmpty(id)) {
            //二级
            if(BaseUtil.SystemLevel.HOSPITALLEVEL.equals(currentSystemLevel)){
                wQbdSoftwareView.setReportStatus(ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED);
            }
            //三级
            if(BaseUtil.SystemLevel.PLANTLEVEL.equals(currentSystemLevel)){
                wQbdSoftwareView.setReportStatus(ZhiLiangConst.REPORT_STATUS_TEMP_TOBEREPORTED);
            }
            SysAuditThreadLocalHolder.putParamerter("isAdd",true);
            wQbdSoftwareView.setBelongdeptname(BaseUtil.getCurrentTenOrgCodePath());
            //新增操作
            //新增数据前生成随机Id
            wQbdSoftwareView.setId(UUIDUtils.getUUIDFor32());
            wQbdSoftwareView.setTenantId(ContextUtil.getCurrentUserTenantId());
            wQbdSoftwareView.setCreateBy(ContextUtil.getCurrentUserId());
            wQbdSoftwareView.setCreateTime(new Date());
            //通用
            wQbdSoftwareView.setFilldept(ContextUtil.getCurrentOrg().getOrgName());
            wQbdSoftwareView.setFilldate(TimeUtil.getCurrentDate());
            wQbdSoftwareView.setFillman(ContextUtil.getCurrentUser().getFullName());
            wQbdSoftwareView.setFillmanaccount(ContextUtil.getCurrentUser().getAccount());
            wQbdSoftwareView.setFilldeptid(((SysOrg) ContextUtil.getCurrentOrg()).getCode());
            result = wQbdSoftwareViewService.add(wQbdSoftwareView);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            WQbdSoftwareView qbdSoftwareView = wQbdSoftwareViewService.getOneById(id);
            String modifyInfo = StructureModifyUtil.getModifyInfo(qbdSoftwareView, wQbdSoftwareView);
            SysAuditThreadLocalHolder.putParamerter("modifyInfo",modifyInfo);
            wQbdSoftwareView.setUpdateBy(ContextUtil.getCurrentUserId());
            wQbdSoftwareView.setUpdateTime(new Date());
            //修改操作
            result = wQbdSoftwareViewService.update(wQbdSoftwareView);
        }
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
     * 功能描述: 跳转到详情页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2020-07-07 13:25:24
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description="跳转到软件概况详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        String isClose=RequestUtil.getString(request,"isClose");
        selectDic(modelMap);
        modelMap.put("id",id);
        modelMap.put("isClose",isClose);
        return "wQbdSoftwareView/particulars";
    }

    /**
     * 功能描述: 根据主键id获取一条数据的通用查询方法
     *
     * @param: id 参数对象必须是"id"
     * @return: java.lang.Object
     * @auther: hw
     * @date: 2020-07-07 13:25:24
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询软件概况的一条数据",detail="根据主键id查询软件概况的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdSoftwareView wQbdSoftwareView = wQbdSoftwareViewService.getOneById(id);
        if (null == wQbdSoftwareView) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("get.success",wQbdSoftwareView);
    }

    /**
     * 功能描述: 根据主键ID删除数据的通用删除方法
     *
     * @param: id 参数名称必须是"id"
     * @return: java.lang.Object
     * @auther: mi
     * @date: 2020-06-22 14:16:42
     */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description = "根据主键ID删除质量综合分析报告数据", exectype = " 删除日志", detail = " 删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id,@RequestParam("datatype") String datatype) {
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            WQbdSoftwareView wQbdSoftwareView = wQbdSoftwareViewService.getOneById(key);
            if ("2".equals(datatype) && Objects.nonNull(wQbdSoftwareView.getReportStatus())
                    && !ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED.equals(wQbdSoftwareView.getReportStatus()))
                   {
                SysAuditThreadLocalHolder.putParamerter("success", false);
//                return fail("删除失败，只允许删除待报集团、报集团审批未通过、报集团失败的数据");
                return fail("删除失败，只允许删除待报集团、待上报的数据");
            }
            if ("1".equals(datatype) && Objects.nonNull(wQbdSoftwareView.getReportStatus())
                    && !ZhiLiangConst.REPORT_STATUS_TEMP_TOBEREPORTED.equals(wQbdSoftwareView.getReportStatus())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只允许删除待报集团、待上报的数据");
            }
            if (!userId.equals(wQbdSoftwareView.getCreateBy())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只能删除自己创建的数据！");
            }
        }
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail("delete.failure.message");
        }
        int result = wQbdSoftwareViewService.delByIdArray(id.split(","));
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return result > 0 ? getResultDataSuccess("delete.success")
                : getResultDataError("delete.failure");
    }

    /**
     * 功能描述: 跳转到导入页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-12-25 19:21:40
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description="跳转到软件概况导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wQbdSoftwareView/import";
    }

    /**
     * 导入资源文件
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/importData")
    @Action(description="导入软件概况资源文件",detail="导入软件概况资源文件<#if success>成功<#else></#if>")
    @ResponseBody
    public ResultData importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success",false);
        MultipartFile multipartFile = request.getFile("file");
        TableEntity excelEntity = new CustomExcelReader().readFile(multipartFile.getInputStream());
        List<WQbdXhdh> xhdhList = wQbdXhdhService.getAll();
        Map<String, Object> map = new AbstractImpUtil() {
            @Override
            public ReturnType customValidation(String fieldName, String fieldValue) {
                ReturnType returnType = null;
                //特殊字段自定义验证
                if("model".equals(fieldName)){
                    returnType = new ReturnType();
                    boolean sign = true;
                    for(WQbdXhdh xhdh : xhdhList){
                        if (xhdh.getfModelname().equals(fieldValue)) {
                            returnType.setNewValue(xhdh.getId());
                            sign = false;
                            break;
                        }
                    }
                    if(sign){
                        returnType.setMsg("非法的值!");
                    }
                }
                if("productCode".equals(fieldName)){
                    returnType = new AbstractImpUtil.ReturnType();
                    boolean sign = true;
                    try {
//                        Integer.parseInt(fieldValue);
//                        Long.parseLong(fieldValue.replace(",",""));
                        returnType.setNewValue(fieldValue.replace(",",""));
                        sign = false;
                    } catch (Throwable t) {
                    }
                    if (sign) {
                        returnType.setMsg("非法的值!");
                    }
                }

                return returnType;
            }
        }.reverseModels(excelEntity, WQbdSoftwareView.class);
        String msg = map.get("msg").toString();
        List<WQbdSoftwareView> list = (List<WQbdSoftwareView>)map.get("instList");
        if(StringUtil.isEmpty(msg)){
            this.wQbdSoftwareViewService.addImportData(list);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("dataSource.importXml.success");
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail(msg);
        }
    }

    /**
     * 功能描述: 跳转到导出选择字段页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-12-25 19:21:40
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description="跳转到软件概况导出选择字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request,ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(WQbdSoftwareView.class);
        modelMap.put("tableInfo",jsonObject.toString());
        return "expImp/add";
    }


    /**
     * 功能描述: 导出软件概况数据信息
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: hw
     * @date: 2020-07-07 13:25:24
     */
    @RequestMapping("/exportData")
    @Action(description="导出软件概况数据信息",detail="导出软件概况数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success",false);
        String[] id = RequestUtil.getStringAryByStr(request,"id");
        QueryFilter queryFilter = new QueryFilter(request,false);
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter,id);
        List<WQbdSoftwareView> wQbdSoftwareViewList = this.wQbdSoftwareViewService.queryAll(queryFilter);
        if(wQbdSoftwareViewList.isEmpty()){
            wQbdSoftwareViewList.add(new WQbdSoftwareView());
        }
        List<WQbdXhdh> xhdhList = wQbdXhdhService.getAll();
        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                if("model".equals(fieldName)){
                    for(WQbdXhdh xhdh : xhdhList){
                        if (xhdh.getId().equals(fieldValue)) {
                            return  xhdh.getfModelname();
                        }
                    }
                }
                return null;
            }
        }.executeExport(request,response,wQbdSoftwareViewList,dataArray, AbstractExpUtil.ExpStyle.MANY_SHEET);
        SysAuditThreadLocalHolder.putParamerter("success",true);
    }

    /**
     * 查询上报的信息
     *
     * @param request
     * @param id
     * @param tableName
     * @return
     */
    @RequestMapping("/reportList")
    @ResponseBody
    public Object reportList(HttpServletRequest request, @RequestParam("id") String id, @RequestParam("tableName") String tableName) {
        //业务数据
        List<WQbdSoftwareView> reportList = wQbdSoftwareViewService.reportList(id, tableName);
        List<Dictionary> xhmcList = getXhdhToDicList();
        reportList.stream().forEach(s->{
            xhmcList.forEach(a -> {
                if (a.getItemValue().equals(s.getModel())) {
                    s.setModel(a.getItemName());
                }
            });
        });
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("options.success", reportList);
    }
}
